<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  * {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }

  a {
    text-decoration: none;
  }

  section {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50%;

  }

  form {
    display: flex;
    justify-content: center;

  }

  li {
    list-style: none;
    display: flex;
    /* justify-content: space-between; */
    border-bottom: 1px solid black;
  }

  li div {
    position: absolute;
    right: 0;
  }

  .list input[type='checkbox']:checked+span {
    text-decoration: line-through;
  }
</style>

<body>
  <section>
    <form action="" autocomplete="off">
      <input type="text" name="massage">
      <button type="submit">提交</button>
    </form>
    <ul class="list">
      
    </ul>
  </section>
  <script>
    const todolist = [
      { id: 1, title: '任务1', isCompleted: false },
      { id: 2, title: '任务2', isCompleted: false },
      { id: 3, title: '任务3', isCompleted: false },
      { id: 4, title: '任务4', isCompleted: false },
      { id: 5, title: '任务5', isCompleted: false },
    ]

    //渲染数据
    const list = document.querySelector('.list')
    function renderList() {
      list.innerHTML = ''
      for (let i = 0; i < todolist.length; i++) {
        const li = document.createElement('li')
        list.appendChild(li)
        li.innerHTML = `
        <input type="checkbox">
        <span data-title="${todolist[i].title}">${todolist[i].title}</span>
        <div><a href="javascript:" data-id="${i}">修改</a>|<a href="javascript:"data-id="${i}">删除</a></div>
        `
      }
    }
    //初始渲染
    renderList()

    //提取用户输入数据并添加到代办事项
    function todo(title) {
      todolist.push({ di: todolist.length + 1, title: title, isCompleted: false })
      //每次添加重新渲染
      renderList()
    }

    //表单提交
    const form = document.querySelector('form')
    form.addEventListener('submit', function (e) {
      //阻止默认事件
      e.preventDefault()
      //获取用户输入信息
      const msg = document.querySelector('[name=massage]').value
      //判断用户是否输入信息
      !msg ? alert('请输入代办任务') : todo(msg)
      //重置表单
      form.reset()
    })

    list.addEventListener('click', function (e) {
      if (e.target.tagName === 'A' && e.target.innerHTML === '删除') {
        todolist.splice(e.target.dataset.id, 1)
        renderList()
      }
      if (e.target.tagName === 'A' && e.target.innerHTML === '修改') {
        const changeValue = prompt('要修改的内容', document.querySelector(`ul li:nth-child(${+e.target.dataset.id + 1}) span`).innerHTML)
        if (!changeValue) {
          todolist.splice(e.target.dataset.id, 1)
        }
        else{
          todolist[e.target.dataset.id].title = changeValue
        }
        renderList()
      }
    })
  </script>
</body>

</html>